import { Fragment, useEffect, useState } from 'react';
import { useRequest } from 'ahooks';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { getMessage, TextWidget } from '@inbiz/react';
import { Checkbox, Collapse, Empty, message, Modal, Spin } from 'antd';
import { InbizIcon } from '@inbiz/utils';
// import { useRequest } from 'ahooks';
import {
  deleteIconById,
  IconGroupType,
  CustomIconType,
  getCustomIConByGroup,
  getCustomIConBySearch,
  SerchDataType,
} from '../service';
// @ts-ignore
import '../index.less';

export type IShowIconsCollapse = {
  groupData: IconGroupType[];
  serchValue: string;
  showIcon: CustomIconType[];
  checkSelectGroup: IconGroupType;
  selected: string;
  alreadyActiveKeys: string[];
  isGroupLoading: boolean;
  setShowIcon: (icons: CustomIconType[]) => void;
  handlePicker: (Id: string, flag?: boolean) => void;
  setCheckSelectGroup: (nowGroup: IconGroupType) => void;
  setAlreadyActiveKeys: (keys: string[]) => void;
  setGroupData: (keys: IconGroupType[]) => void;
  setIsGroupLoading: (isGroupLoading: boolean) => void;
  isHideTitle?:boolean;
};

const { Panel } = Collapse;
const { confirm } = Modal;
const ShowIconsCollapse = (props: IShowIconsCollapse) => {
  const {
    groupData,
    showIcon,
    selected,
    checkSelectGroup,
    serchValue,
    alreadyActiveKeys,
    isGroupLoading,
    setGroupData,
    setAlreadyActiveKeys,
    handlePicker,
    setCheckSelectGroup,
    setShowIcon,
    setIsGroupLoading,
    isHideTitle
  } = props;
  const [activeKey, setActiveKey] = useState<string[]>([]);
  const [addKeys, setAddKeys] = useState<string[]>([]);
  // 已经加载了的分组图标(防止多次调用加载数据)

  const deleteIconByIdApi = useRequest(deleteIconById, {
    manual: true,
  });
  const getCustomIConByGroupApi = useRequest(getCustomIConByGroup, {
    manual: true,
  });
  const getCustomIConBySearchApi = useRequest(getCustomIConBySearch, {
    manual: true,
  });

  useEffect(() => {
    if (serchValue && serchValue.length > 0) {
      setIsGroupLoading(true);
      getCustomIConBySearchApi.runAsync({ serchText: serchValue }).then((data: any) => {
        let groups: IconGroupType[] = [];
        let groupsIds: string[] = [];
        let icons: CustomIconType[] = [];
        data.forEach((item: SerchDataType) => {
          const { IconDtos, ...nowGroup } = item;
          groups.push(nowGroup);
          groupsIds.push(nowGroup.OutId);
          icons.push(...IconDtos);
        });
        setShowIcon(icons);
        setAlreadyActiveKeys(groupsIds);
        setGroupData(groups);
        setActiveKey(groupsIds);
        setIsGroupLoading(false);
      });
    } else if (!serchValue || serchValue.length === 0) {
      setShowIcon([]);
      setAlreadyActiveKeys([]);
      setActiveKey([]);
    }
  }, [serchValue]);

  // 获取图标数据
  useEffect(() => {
    if (getCustomIConByGroupApi.data && getCustomIConByGroupApi.loading == false) {
      const nowData: any = getCustomIConByGroupApi.data;
      setShowIcon([...showIcon, ...nowData.flat(Infinity)]);
    }
    if (getCustomIConByGroupApi.loading) {
      console.log(getMessage('IconPicker.getIconDataLoading'));
    }
    if (getCustomIConByGroupApi.error) {
      console.log(getMessage('IconPicker.getIconDataError'));
    }
  }, [
    getCustomIConByGroupApi.data,
    getCustomIConByGroupApi.loading,
    getCustomIConByGroupApi.error,
  ]);

  // 完成默认展开项
  useEffect(() => {
    if (alreadyActiveKeys.length === 0 && groupData.length != 0) {
      const openGroup = [];
      if (groupData?.length > 2) {
        for (let index = 0; index < 3; index++) {
          openGroup.push(groupData[index].OutId);
        }
      } else {
        groupData?.length > 0 &&
          groupData.forEach((item) => {
            openGroup.push(item.OutId);
          });
      }
      setAddKeys(openGroup);
      setActiveKey([...activeKey, ...openGroup]);
    }
  }, [groupData, alreadyActiveKeys]);

  useEffect(() => {
    if (addKeys.length === 1 && alreadyActiveKeys?.indexOf(addKeys[0]) === -1) {
      setAlreadyActiveKeys([...alreadyActiveKeys, addKeys[0]]);
      getCustomIConByGroupApi.runAsync({ outId: addKeys[0], serchText: serchValue });
    } else if (addKeys.length > 1) {
      setAlreadyActiveKeys([...alreadyActiveKeys, ...addKeys]);
      getCustomIConByGroupApi.runAsync({ outId: addKeys, serchText: serchValue });
    }
  }, [addKeys]);
  // 选中
  const genExtra = (nowGroup: IconGroupType) => (
    <Checkbox
      onClick={(e: any) => {
        // If you don't want click extra trigger collapse, you can prevent this:
        if (e.target.checked) {
          setCheckSelectGroup(nowGroup);
        } else {
          setCheckSelectGroup({
            Id: '',
            IsDefault: false,
            OutId: '',
            AppId: '',
            Name: '',
          });
        }
        e.stopPropagation();
      }}
      defaultChecked={checkSelectGroup.Id == nowGroup.Id}
      checked={checkSelectGroup.Id === nowGroup.Id}
    />
  );

  function showIconDeleteConfirm(Id: string) {
    confirm({
      title: getMessage('IconPicker.deleteIcon'),
      icon: <ExclamationCircleOutlined />,
      content: getMessage('IconPicker.sureDeleteIcon') + '?',
      okText: getMessage('IconPicker.okText'),
      cancelText: getMessage('IconPicker.cancelText'),
      centered: true,
      onOk() {
        deleteIconByIdApi.runAsync({ Id }).then((data) => {
          if (!data) return;
          message.success(getMessage('IconPicker.deleteSuccess'));
          const nowIcon = showIcon.filter((item) => {
            return item.Id !== Id;
          });
          setShowIcon(nowIcon);
        });
      },
    });
  }

  // 分组管理
  const collapseOnChange = (keys: string[]) => {
    const nowAddKeys = keys?.filter((item) => {
      return activeKey?.indexOf(item) === -1;
    });
    nowAddKeys.length > 0 && setAddKeys(nowAddKeys);
    setActiveKey(keys);
  };

  /**
   * 字符串比较,可能存在{AppId}等情况
   * "/inbiz/static/3a047f62f43ce274c7c6437a4c3d604a/file/2022-10-27/c32d3c5e555647eeb05ff7e3073d2ffb.svg"
   * "/inbiz/static/{AppId}/file/2022-10-27/c32d3c5e555647eeb05ff7e3073d2ffb.svg"
   * @param strA
   * @param strB
   * @returns Boolean
   */
  const stringCompare = (strA: string, strB: string) => {
    let result = false;
    try {
      if (strA.split('/').slice(-1)[0] == strB.split('/').slice(-1)[0]) {
        result = true;
      }
    } catch (err) { }
    return result;
  };

  return (
    // @ts-ignore
    <Collapse ghost expandIconPosition={'right'} onChange={collapseOnChange} activeKey={activeKey}>
      <div className="divider"></div>
      {!isGroupLoading ? (
        groupData?.length > 0 ? (
          groupData.map((nowGroup) => {
            const nowGroupIcon = showIcon.filter((nowIcon: CustomIconType) => {
              return nowIcon.IconGroupOutId === nowGroup.OutId;
            });

            return (
              <Fragment key={nowGroup.Id}>
                <Panel
                  header={nowGroup.Name}
                  key={nowGroup.OutId}
                  className="customIconContent"
                  extra={genExtra(nowGroup)}
                >
                  <div
                    style={{
                      display: 'flex',
                      flexWrap: 'wrap',
                      paddingTop: 4,
                      alignContent: 'flex-start',
                    }}
                  >
                    {nowGroupIcon?.length > 0 ? (
                      nowGroupIcon.map((nowIcon, index) => {
                        return (
                          <div
                            className={
                              'iconPicker' +
                              ' ' +
                              (stringCompare(selected, nowIcon.Path) ||
                                nowGroup.Id === checkSelectGroup.Id
                                ? 'selected'
                                : '')
                            }
                            title={nowIcon.Name}
                            onClick={() => handlePicker(nowIcon.Path, nowIcon.RemoveColor)}
                            key={nowIcon.Id}
                            style={{height:isHideTitle?'36px':'72px'}}
                          >
                            <InbizIcon type={nowIcon.Path} style={{ width: 21, height: 21 }} />
                            <span className="iconPickerText" style={{ display: isHideTitle ? 'none' : 'block' }}>{nowIcon.Name}</span>
                            <div className="deleteIconContent">
                              <InbizIcon
                                className="deleteIcon"
                                onClick={() => {
                                  showIconDeleteConfirm(nowIcon.Id);
                                }}
                                type="icon-ic-clear"
                              />
                            </div>
                          </div>
                        );
                      })
                    ) : alreadyActiveKeys?.indexOf(nowGroup.OutId) !== -1 &&
                      addKeys?.indexOf(nowGroup.OutId) === -1 ? (
                      <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={<TextWidget>pageselect.no_data</TextWidget>}
                      />
                    ) : getCustomIConByGroupApi.loading ? (
                      <Spin style={{ width: '100%' }} />
                    ) : (
                      <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={<TextWidget>pageselect.no_data</TextWidget>}
                      />
                    )}
                  </div>
                </Panel>
                <div className="divider"></div>
              </Fragment>
            );
          })
        ) : (
          <div>
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={<TextWidget>pageselect.no_data</TextWidget>}
            />
          </div>
        )
      ) : (
        <div className="groupLoading">
          <Spin />
        </div>
      )}
    </Collapse>
  );
};

export default ShowIconsCollapse;
